<template>
  <div class="app-container">
    <el-row class="mb-3" >
      <el-button type="primary"
                 icon="CirclePlus"
                 plain
                 @click="addVoiceBroadcastList"
                 v-hasPermi="['core:broadcast:add']">新增</el-button>
      <el-button type="success"
                 icon="Edit"
                 plain
                 :disabled="single"
                 @click="editVoiceBroadcast"
                 v-hasPermi="['core:broadcast:edit']">编辑</el-button>
      <el-button type="danger"
                 icon="Delete"
                 plain
                 :disabled="multiple"
                 @click="deleteBroadcast"
                 v-hasPermi="['core:broadcast:remove']">删除</el-button>
    </el-row>
  </div>
  <div class="table-broadcast mb8">
    <el-table :data="voiceBroadcastList"
              border
              stripe
              ref="voiceBroadcastList"
              v-loading="recordLoading"
              @selection-change="selectionChange">
      <el-table-column align="center" type="selection"/>
      <el-table-column align="center" type="index" label="序号" width="80"/>
      <el-table-column align="center" prop="content" label="发送内容"/>
      <el-table-column align="center" prop="receiver" label="接收方">
        <template #default="scope">
          <span>{{getUser(scope.row.receiver)}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="frequencyType" label="频率">
        <template #default="scope">
          <el-tag :type="scope.row.frequencyType===1? 'success':scope.row.frequencyType===2? 'primary':'danger'">{{(scope.row.frequencyType)=== 1? '单次':scope.row.frequencyType===2? '间隔':'异常'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="startTime" label="开始时间"/>
      <el-table-column align="center" prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status===0? 'success':scope.row.status===1? 'danger':'warning'">{{(scope.row.status)=== 0? '已发送':scope.row.status===1? '未启用':'异常'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="operation" label="操作">
        <template #default="scope">
          <el-button
            type="success"
            plain
            @click="handleSend(scope.row)"
            v-hasPermi="['core:broadcast:changeStatus']">发送</el-button>
          <el-button
              type="danger"
              plain
              @click="handleStop(scope.row)"
              v-hasPermi="['core:broadcast:changeStatus']">停止</el-button>
        </template>

      </el-table-column>
    </el-table>

</div>
  <el-dialog v-model="dialogBroadcast"
             height="100hv"
             width="800px"
             :before-close="handleClose"
             :title="stateTitle ? '添加广播信息':'编辑广播信息'" >
    <el-form :model="form" :rules="rules" ref="formRef" class="form">
      <el-form-item label="请输入信息" prop="content">
        <el-input v-model="form.content"
                  type="textarea"
                  placeholder="请填写需要发送的信息"
                  :row="2"
                  :maxlength="140"
                  show-word-limit/>
      </el-form-item>
      <el-form-item label="接收人员" prop="receiver">
        <users-select v-model="form.receiver" width="200px"></users-select>
      </el-form-item>
<!--      <el-form-item v-show="false" label="接收类型" prop="receiverType">
        <el-input v-model="form.receiveType"></el-input>
      </el-form-item>-->
      <el-form-item label="播放频率" prop="frequencyType" >
        <el-select v-model="form.frequencyType" placeholder="请选择" >
          <el-option label="单次" :value = '1' >单次</el-option>
          <el-option label="间隔" :value = '2' >间隔</el-option>
        </el-select>
        <div v-if="form.frequencyType === 2" >
          <el-form-item>
            <el-input v-model="form.frequencyInterval" placeholder="请输入间隔"></el-input>
          </el-form-item>
        </div>
        <div v-if="form.frequencyType ===2">
          <el-form-item>
            <el-select v-model="form.frequencyUnit" >
              <el-option label="秒" :value="1">秒</el-option>
              <el-option label="分" :value="2">分</el-option>
              <el-option label="时" :value="3">时</el-option>
              <el-option label="日" :value="4">日</el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form-item>
      <el-form-item label="开始时间" prop="startType" >
        <el-select v-model="form.startType" >
          <el-option label="选择时间" :value="2">指定时间</el-option>
        </el-select>
        <div v-if="form.startType === 2">
          <el-form-item label="   ">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="YYYY-MM-DD HH:mm:ss" >
            </el-date-picker>
          </el-form-item>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button v-show="stateTitle === true " @click="cancel">保存草稿</el-button>
      <el-button v-show="stateTitle === false " @click="cancel" >取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
  <pagination :total="recordTotal"
              v-model:page="queryForm.pageNum"
              v-model:limit="queryForm.pageSize"
              @pagination="getVoiceBroadcastList"/>
</template>

<script>
import {
  getVoiceBroadcastList,
  deleteVoiceBroadcast,
  addVoiceBroadcast,
  getVoiceBroadcast,
  updateVoiceBroadcast,
  msgSend,
  msgCancel,
} from "../../../api/core/voiceBroadcast";
import {getUserByNickName} from "../../../api/system/user"

export default {
  name: "index",
  data() {
    return {
      queryForm: {
        pageNum: 1,
        pageSize: 10
      },
      recordLoading: false,
      voiceBroadcastList: [],
      recordTotal: 0,
      stateTitle:true,
      ids:[],
      single:true,
      multiple:true,
      dialogBroadcast:false,
      rules:{},
      form:{},
      allUserMap: {}
      }
    },
    created() {
      this.getVoiceBroadcastList()
      this.getUserMap()
    },
  methods: {
    getUserMap() {
      getUserByNickName().then(res=>{
        console.log("2333",res)
        this.allUserMap = res.data
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    resetQueryForm() {
      this.queryForm = {
        pageNum: 1,
        pageSize: 10
      }
      this.getVoiceBroadcastList()
    },
    getVoiceBroadcastList() {
      this.recordLoading = true
      getVoiceBroadcastList(this.queryForm).then(res => {
        const {rows, total} = res
        this.voiceBroadcastList = rows
        this.recordTotal = total
        res.userId

      }).finally(() => {
          this.recordLoading = false
        }
      )
    },
    selectionChange(selection){
      console.log(selection)
      this.single =selection.length !==1
      this.multiple = !selection.length
    },
    addVoiceBroadcastList(){
      this.dialogBroadcast = true
      this.stateTitle=true
    },
    deleteBroadcast(){
      const rows = this.$refs.voiceBroadcastList.getSelectionRows()
      const ids = rows.map(item => item.id)
       this.$modal.confirm('您确定要删除勾选的数据吗？').then(function (){
         console.log(ids)
        return deleteVoiceBroadcast(ids)
      }).then(()=>{
        this.getVoiceBroadcastList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {});
    },
    cancel(){
      if(this.stateTitle === false){
        this.reset()
        this.dialogBroadcast = false
      }else{
        this.dialogBroadcast =false
      }
    },
    reset(){
      this.resetForm("formRef")
      this.form ={}
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate()
      }
    },
    submitForm(){
      this.$refs.formRef.validate(valid =>{
        if(valid) {
          if (this.stateTitle === false) {
            this.form.frequencyType = this.form.frequencyType-0
            this.form.frequencyInterval = this.form.frequencyInterval - 0
            this.form.frequencyUnit = this.form.frequencyUnit - 0
            this.form.startType = this.form.startType - 0
            this.form.receiveType = this.form.receiveType-0
            this.form.receiver = this.form.receiver.toString()
            updateVoiceBroadcast(this.form).then(res => {
              this.$modal.msgSuccess('修改成功')
              this.getVoiceBroadcastList()
              this.dialogBroadcast = false
            })
          } else {
            this.form.frequencyType = this.form.frequencyType - 0
            this.form.frequencyInterval = this.form.frequencyInterval - 0
            this.form.frequencyUnit = this.form.frequencyUnit - 0
            this.form.startType = this.form.startType - 0
            addVoiceBroadcast(this.form).then((res) => {
              console.log(res)
              this.getVoiceBroadcastList()
              this.$modal.msgSuccess("添加成功")
              this.dialogBroadcast = false
            })
          }
        }
      })
    },
    editVoiceBroadcast(){
      this.stateTitle = false
      const rows = this.$refs.voiceBroadcastList.getSelectionRows()
      const id = {...rows.map(item =>item.id)}
      console.log('22334',id);
      getVoiceBroadcast(id[0]).then(res =>{
        console.log(res);
        this.form = {
          content: res.data.content,
          receiver: res.data.receiver,
          receiveType: res.data.receiveType,
          jobId:res.data.jobId,
          frequencyType:res.data.frequencyType,
          frequencyInterval:res.data.frequencyInterval,
          frequencyUnit:res.data.frequencyUnit,
          startType:res.data.startType,
          startTime: res.data.startTime,
          id:res.data.id,
        }
      })
      this.dialogBroadcast = true
    },
    getUser(str){
      if(!str){
        return str
      }else{
        let arr = str.split(',')
        let receiverArr = arr.map(item => this.allUserMap[item])
        return receiverArr.join(',')
      }
    },
    handleSend(row){
      msgSend({
        id: row.id,
        jobId: row.jobId
        }).then(res=>{
        console.log(res);
        this.$modal.msgSuccess('发送成功')
        this.$router.go(0);
        window.location.reload();
      })
    },

    handleStop(row){
      msgCancel({
        id: row.id,
        jobId: row.jobId
        }).then(res=>{
        console.log(res);
        this.$modal.msgSuccess('停止发送成功')
        this.$router.go(0);
        window.location.reload();

      })
    },
  }
}
</script>
<style lang="scss" scoped>
.el-table .el-table__cell
{
  padding: 5px 0;
}
.map-container {
  height: 500px;
}
.app-container {
  padding: 10px;
}
</style>

